package main

import (
	"net/http"

	"github.com/gorilla/mux"
)

type Service struct {
	Name    string
	URL     string
	Port    int
	Enabled bool
}

var services = map[string]Service{
	"user-service": {
		Name:    "user-service",
		URL:     "localhost",
		Port:    8081,
		Enabled: true,
	},
}

func SetupRouting(router *mux.Router, services map[string]Service) {
	for _, service := range services {
		if !service.Enabled {
			continue
		}
		path := "/" + service.Name + "/{everything:.*}"
		router.Path(path).HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			target := service.URL + ":" + string(service.Port) + r.URL.Path
			// w.Write([]byte("Proxying to " + target))
			proxyRequest(w, r, target)
		})
	}
}

func proxyRequest(w http.ResponseWriter, r *http.Request, target string) {
	req, err := http.NewRequest(r.Method, target, r.Body)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		http.Error(w, err.Error(), http.StatusServiceUnavailable)
		return
	}
	for k, v := range resp.Header {
		w.Header().Set(k, v[0])
	}
	w.WriteHeader(resp.StatusCode)
	resp.Write(w)
}
